<template>
  <view class="container">
    <uni-section title="基本用法" type="line">
      <view class="example">
        <!--  -->
        <uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules">
          <uni-forms-item label="姓名" required name="uname">
            <uni-easyinput v-model="baseFormData.uname" placeholder=" " />
          </uni-forms-item>
          <uni-forms-item label="性别" required name="staffsex">
            <uni-data-checkbox
              v-model="baseFormData.staffsex"
              :localdata="sexs"
            />
          </uni-forms-item>
          <uni-forms-item label="手机号码" required name="umobile">
            <uni-easyinput v-model="baseFormData.umobile" placeholder=" " />
          </uni-forms-item>

          <uni-forms-item label="身份证号码" name="ucardid">
            <uni-easyinput v-model="baseFormData.ucardid" placeholder=" " />
          </uni-forms-item>

          <uni-forms-item label="工作日期" name="uworkdate">
            <uni-datetime-picker
              type="datetime"
              return-type="timestamp"
              v-model="baseFormData.uworkdate"
              @change="changeData"
            />
          </uni-forms-item>

          <uni-forms-item label="学历" required name="educationid">
            <uni-data-select
              v-model="baseFormData.educationid"
              placeholder=" "
              :localdata="rangeEucation"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="学历取得日期" name="educationdate">
            <uni-datetime-picker
              type="datetime"
              return-type="timestamp"
              v-model="baseFormData.educationdate"
              @change="changeData"
            />
          </uni-forms-item>

          <uni-forms-item label="证件类型" required name="staffcerttypeid">
            <uni-data-select
              v-model="baseFormData.staffcerttypeid"
              placeholder=" "
              :localdata="rangeStaType"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="证件号" required name="staffcertno">
            <uni-easyinput v-model="baseFormData.staffcertno" placeholder=" " />
          </uni-forms-item>

          <uni-forms-item  v-if="false" label="是否认证" required name="realnamestatus">
            <uni-data-checkbox
              v-model="baseFormData.realnamestatus"
              :localdata="realnamestatus"
            />
          </uni-forms-item>

          <uni-forms-item label="临床年限" name="workyears">
            <uni-easyinput v-model="baseFormData.workyears" placeholder=" " />
          </uni-forms-item>

          <uni-forms-item label="民族" required name="nationid">
            <uni-data-select
              v-model="baseFormData.nationid"
              placeholder=" "
              :localdata="rangeNation"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item
            label="资格证书编码"
            required
            name="qualificationcode"
          >
            <uni-easyinput
              v-model="baseFormData.qualificationcode"
              placeholder=" "
            />
          </uni-forms-item>

          <uni-forms-item label="执业证书编码" required name="practicecode">
            <uni-easyinput
              v-model="baseFormData.practicecode"
              placeholder=" "
            />
          </uni-forms-item>

          <uni-forms-item
            label="第一执业机构编码"
            required
            name="firstpractisingorgcode"
          >
            <uni-easyinput
              v-model="baseFormData.firstpractisingorgcode"
              placeholder=" "
            />
          </uni-forms-item>

          <uni-forms-item
            label="第一执业机构名称"
            required
            name="firstpractisingorgname"
          >
            <uni-easyinput
              v-model="baseFormData.firstpractisingorgname"
              placeholder=" "
            />
          </uni-forms-item>

          <uni-forms-item label="执业证书发证日期" name="practicedate">
            <uni-datetime-picker
              type="datetime"
              return-type="timestamp"
              v-model="baseFormData.practicedate"
              @change="changeData"
            />
          </uni-forms-item>

          <uni-forms-item label="人员职称" required name="titleid">
            <uni-data-select
              v-model="baseFormData.titleid"
              placeholder=" "
              :localdata="rangeTitle"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="执业类别" required name="practicetype">
            <uni-data-checkbox
              v-model="baseFormData.practicetype"
              :localdata="practicetype"
            />
          </uni-forms-item>

          <uni-forms-item v-if="false"  label="是否备案" required name="filingmark">
            <uni-data-checkbox
              v-model="baseFormData.filingmark"
              :localdata="filingmark"
            />
          </uni-forms-item>

          <uni-forms-item label="出生日期" name="staffbirthday">
            <uni-datetime-picker
              type="datetime"
              return-type="timestamp"
              v-model="baseFormData.staffbirthday"
              @change="changeData"
            />
          </uni-forms-item>

          <uni-forms-item label="医疗人员图片" required name="staffpic">
            <button @click="reviewImage(0)">上传图片</button>
          </uni-forms-item>

          <uni-forms-item label="就职医院" required name="ucompid">
            <uni-data-select
              v-model="baseFormData.ucompid"
              placeholder="必填"
              :localdata="range2"
              @change="change2"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="业务类型" required name="businesstype">
            <uni-data-checkbox
              v-model="baseFormData.businesstype"
              multiple
              :localdata="rangeBusiness"
            />
          </uni-forms-item>

          <uni-forms-item label="就职科室" required name="deptid">
            <uni-data-checkbox
              v-model="baseFormData.deptid"
              multiple
              :localdata="rangeSubjectBig"
            />
          </uni-forms-item>

          <uni-forms-item label="就职科目" required name="subjectcode">
            <uni-data-checkbox
              v-model="baseFormData.subjectcode"
              multiple
              :localdata="rangeSubjectSmall"
            />
          </uni-forms-item>

          <button type="primary" @click="picodoneAction12('valiForm')">
            提交
          </button>
        </uni-forms>
      </view>
    </uni-section>
  </view>
</template>


<script>
import { pathToBase64, base64ToPath } from "image-tools";
export default {
  methods: {
    reviewImage: function (position) {
      let that = this;
      console.log("reviewImage");
      uni.chooseImage({
        count: 1,
        sourceType: ["album", "camera"],
        sizeType: ["compressed", "original"],
        success: (imageres) => {
          console.log(imageres, "imageres");

          /* 判断大小 */
          // let size = imageres.tempFiles[0].size;
          // if (this.baseBig(size)) {
          //   console.log("small");
          // } else {
          //   console.log("big");
          //   uni.showToast({
          //     title: "上传不能大于50kb",
          //   });
          //   return;
          // }
          this.uploaderImagePath(position, imageres.tempFilePaths[0]);
        },
        fail: (err) => {
          // #ifdef MP
          uni.getSetting({
            success: (res) => {
              let authStatus =
                res.authSetting["scope.album"] &&
                res.authSetting["scope.camera"];
              if (!authStatus) {
                uni.showModal({
                  title: "授权失败",
                  content:
                    "Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限",
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                  },
                });
              }
            },
          });
          // #endif
        },
      });
    },
    uploaderImagePath(position, uploadFileRes) {
      let that = this;
      uni.uploadFile({
        url: this.$url + "/upload/image",
        header: {
          Authorization: uni.getStorageSync("token"),
        },
        filePath: uploadFileRes,
        name: "file",
        success: (uploadFileRes) => {
          console.log(uploadFileRes, "uploadFileRes");
          // let imgUrl = that.$url + uploadFileRes.data;

          let jsondata = JSON.parse(uploadFileRes.data);

          let imgUrl = jsondata.data.fileUrl;

          // 图片转basee64 io操作 使用异步方式
          // function getBase64(img) {
          //     return new Promise(function (resolve, reject) {
          //         const FSM = wx.getFileSystemManager();
          //         FSM.readFile({
          //             filePath: img,
          //             encoding: 'base64',
          //             success(data) {
          //                 resolve(data)
          //             }
          //         })
          //     })
          // }

          // let base62 =  getBase64(imgUrl)

          // console.log(base62, "base62");
          switch (position) {
            case 0:
              this.baseFormData.staffpic = imgUrl;
              // console.log('1')
              // console.log(pathToBase64)
              // pathToBase64(imgUrl).then(data => {
              // 	console.log('2')
              // 	this.baseFormData.staffpic = data;
              // })
              // console.log('3')
              break;
            case 1:
              this.form.uidcardzPic = imgUrl;
              break;
            case 2:
              this.form.uidcardfPic = imgUrl;
              break;
            case 3:
              this.form.upracticingPic = imgUrl;
              break;
          }
        },
      });
    },

    baseBig(fileSize) {
      // 判断图片文件大小是否超过限制
      function isImageSizeValid(fileSize, maxSizeInBytes) {
        return fileSize <= maxSizeInBytes;
      }
      // 测试例子
      var maxSizeInBytes = 50 * 1024; // 50KB
      var isSizeValid = isImageSizeValid(fileSize, maxSizeInBytes);
      return isSizeValid;
    },

    change2(e) {
      console.log(e, "e");
      this.baseFormData.ucompId = e;
    },
    change1(e) {
      console.log(e, "e");
      this.baseFormData.udepartmentid = e;
    },
    changeData(e) {
      console.log(e, "e");
    },

    /* api */
    async getBusinessType() {
      let that = this;
      let re = await this.$API.dictionaryApi.getBusinessType();
      // console.log(re, "re");
      that.rangeBusiness = re.map((i) => {
        // businessType
        return {
          value: i.businessType,
          text: i.businessType,
        };
      });
    },
    async getEducation() {
      let that = this;
      let re = await this.$API.dictionaryApi.getEducation();
      // console.log(re, "re");
      that.rangeEucation = re.map((i) => {
        return {
          value: i.id,
          text: i.educationName,
        };
      });
    },
    /*  */
    async getStaffCert() {
      let that = this;
      let re = await this.$API.dictionaryApi.getStaffCert();
      // console.log(re, "re");
      that.rangeStaType = re.map((i) => {
        return {
          value: i.id,
          text: i.certTypeName,
        };
      });
    },
    async getNation() {
      let that = this;
      let re = await this.$API.dictionaryApi.getNation();
      console.log(re, "re");
      that.rangeNation = re.map((i) => {
        return {
          value: i.id,
          text: i.nationName,
        };
      });
    },
    /* 小类 */
    async getSubjectCodeOne(code) {
      let that = this;
      let re = await this.$API.dictionaryApi.getSubjectCode(code);
      console.log(re, "re");
      that.rangeSubjectSmall = re.map((i) => {
        return {
          value: i.subjectCode,
          text: i.subjectName,
        };
      });
    },
    /* 大类 */
    async getSubjectCodeTwo(code) {
      let that = this;
      let re = await this.$API.dictionaryApi.getSubjectCode(code);
      // console.log(re, "re");
      that.rangeSubjectBig = re.map((i) => {
        return {
          value: i.subjectCode,
          text: i.subjectName,
        };
      });
    },
    async getTitle() {
      let that = this;
      let re = await this.$API.dictionaryApi.getTitle();
      // console.log(re, "re");
      that.rangeTitle = re.map((i) => {
        return {
          value: i.id,
          text: i.titleName,
        };
      });
    },
    /* 医院 */
    async getCompartmentName() {
      let that = this;
      let re = await this.$API.doctorApi.getCompartmentName();
      // console.log(re, "re");
      that.range2 = re.map((i) => {
        return {
          value: i.ucompid,
          text: i.ucompname,
        };
      });
      // console.log(this.range2, "range2");
    },

    /*  */
    picodoneAction12() {
      let that = this;

      /* 补充字段 */
      this.baseFormData.subjectname = this.baseFormData.subjectcode.map(
        (code) => {
          let item = this.rangeSubjectSmall.find((obj) => obj.value === code);
          console.log(item, "item");
          return item ? item.text : null;
        }
      );
      this.baseFormData.deptname = this.baseFormData.deptid.map((code) => {
        let item = this.rangeSubjectBig.find((obj) => obj.value === code);
        console.log(item, "item");
        return item ? item.text : null;
      });

      /* 校验 */
      this.$refs.baseForm
        .validate()
        .then(async (res) => {
          console.log("表单数据信息：", res);
          function allPropertiesHaveValue(obj) {
            return Object.values(obj).every(
              (value) => value !== null && value !== undefined && value !== ""
            );
          }
          if (allPropertiesHaveValue(res)) {
            let re = await this.$API.doctorApi.doctorAuthApply(
              this.baseFormData
            );
            /* 认证页面 */
			uni.navigateBack()
            // uni.reLaunch({
            //   url: "/pages/index/index",
            // });
            console.log(re, "re");
          } else {
            console.log("有一项数据没有值");
          }
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },

    submit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log("success", res);
          uni.showToast({
            title: `校验通过`,
          });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
  },
  onLoad() {
    /*  */
    this.getCompartmentName();

    /*  */
    this.getEducation();
    /*  */
    this.getStaffCert();
    /*  */
    this.getNation();
    /*  */
    this.getTitle();
    /*  */
    this.getBusinessType();
  },
  onShow() {
    /*  */
    this.getSubjectCodeOne(0);
    this.getSubjectCodeTwo(1);
  },
  // onReady() {
  // 	// 设置自定义表单校验规则，必须在节点渲染完毕后执行
  // 	// #ifdef MP
  // 	this.$refs.customForm.setRules(this.customRules)
  // 	// #endif
  // },
  data() {
    return {
      /*  */
      rangeBusiness: [],
      rangeEucation: [],
      rangeStaType: [],
      rangeNation: [],
      /*  */
      rangeSubject: [],
      rangeSubjectBig: [],
      rangeSubjectSmall: [],
      /*  */
      rangeTitle: [],
      range1: [],
      range2: [],

      // 基础表单数据
      baseFormData: {
        uname: "",
        ucardid: "",
        umobile: "",
        ucompId: "",
        udepartmentid: "",
        educationid: "",

        uworkdate: "",
        educationdate: "",

        staffcerttypeid: "",
        staffcertno: "",

        realnamestatus: "",

        workyears: "",

        nationid: "",

        /*  */

        subjectcode: "",
        subjectname: "",
        deptid: "",
        deptname: "",
        /*  */

        qualificationcode: "",
        practicecode: "",
        firstpractisingorgcode: "",
        firstpractisingorgname: "",

        practicedate: "",

        titleid: "",

        practicetype: "",

        filingmark: "",

        staffbirthday: "",

        staffpic: "",

        staffsex: "",
        businesstype: "",
      },
      // 单选数据源
      sexs: [
        {
          text: "男",
          value: 0,
        },
        {
          text: "女",
          value: 1,
        },
        {
          text: "保密",
          value: 2,
        },
      ],
      realnamestatus: [
        {
          text: "未实名",
          value: 0,
        },
        {
          text: "实名",
          value: 1,
        },
      ],
      practicetype: [
        {
          text: "医生",
          value: 1,
        },
        {
          text: "护士",
          value: 2,
        },
        {
          text: "药师",
          value: 3,
        },
      ],
      filingmark: [
        {
          text: "不备案",
          value: 0,
        },
        {
          text: "备案",
          value: 1,
        },
      ],
      // 校验规则
      rules: {
        ucompId: {
          rules: [
            {
              required: true,
              errorMessage: "医院不能为空",
            },
          ],
        },
        udepartmentid: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        uname: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        umobile: {
          rules: [
            {
              required: true,
              errorMessage: "请填写手机号码",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                  /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/; //手机号码
                if (!iphoneReg.test(value)) {
                  callback("手机号码格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        ucardid: {
          rules: [
            {
              required: true,
              errorMessage: "请填写身份证",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                  /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; //
                if (!iphoneReg.test(value)) {
                  callback("身份证格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        uworkdate: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        practicecode: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        educationid: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        educationdate: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        staffcertno: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        titleid: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        staffcerttypeid: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        realnamestatus: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        workyears: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
			{
				format: 'number',
				errorMessage: '只能输入数字'
			},
          ],
        },

        nationid: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        subjectcode: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        staffbirthday: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
        qualificationcode: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        firstpractisingorgcode: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        firstpractisingorgname: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        practicedate: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        practicetype: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        filingmark: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        staffpic: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        staffsex: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },

        businesstype: {
          rules: [
            {
              required: true,
              errorMessage: "不能为空",
            },
          ],
        },
      },
    };
  },
  /*  */
};
</script>
<style lang="scss" scoped>
.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  margin-left: 10px;
}
</style>